
#include <cstring>
#include <stdexcept>

#include <sstream>
#include <fstream>

#include <boost/filesystem.hpp>

#include "boque/trasit/handler.hpp"


class	SimpleHandler	
	:	public boque::trasit::Handler
{

public	:
	SimpleHandler( const char* filename )
		:	_filename_p( filename ),
			_ofs( _filename_p )
	{
	}

	virtual	~SimpleHandler()
	{
		if ( _ofs.is_open() ) {
			_ofs.close();
		}
	}

public	:

	int		handle( const std::string& data )
	{
		_ofs << data << std::endl;

		return	0;
	}


private	:
	const char*	_filename_p;

	std::ofstream	_ofs;
};


extern	"C"
boque::trasit::Handler*
create( const char* p1, const char* p2)
{
	if ( strlen(p1) < 1 ) {
		std::ostringstream	msg;
		msg << "handler-p1 should be path to output file";
		throw std::runtime_error( msg.str() );
	}

	boost::filesystem::path	path1( p1 );
	boost::filesystem::path	p_path1 = path1.parent_path();
	if ( !boost::filesystem::exists( p_path1 ) ) {
        try {
            boost::filesystem::create_directories( p_path1 );
        }   
        catch ( std::exception& e ) { 
            std::ostringstream  msg;
            msg << "fail to create directories " << p_path1.string() << " -- " << e.what();
            throw   std::runtime_error( msg.str() );
        }   
	}

	SimpleHandler*	handler_p = new SimpleHandler( p1 );

	return	handler_p;
}


extern	"C"
void
destroy( boque::trasit::Handler* p ) 
{
	if ( NULL != p ) {
		delete p;
	}
}

